using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Machine.Specifications;
using Machine.Specifications.Runner.Impl;
using Raven.Client;
using Sponsorship.Domain;
using Sponsorship.Infrastructure.BootStrapping.Registries;
using Sponsorship.ReadModel;
using StructureMap;

namespace Sponsorship.Specs.Events
{
    public class when_the_ioc_container_is_setup_with_the_eventHandlerRegistry
    {
        static IEnumerable<Type> _eventList;
        static readonly IDictionary<Type, IList> _eventHandlerList = new Dictionary<Type, IList>(); 

        Establish context = () =>
        {
            _eventList = typeof(IEvent).Assembly.GetTypes().Where(x => x.GetInterface(typeof(IEvent).Name) != null);
            ObjectFactory.Initialize(x =>
                                         {
                                             x.AddRegistry(new EventHandlerRegistry());
                                             x.For<IDocumentStore>().Use<FakeDocumentStore>();
                                         });
        };

        Because of = () => _eventList.ForEach(x => _eventHandlerList.Add(x, ObjectFactory.GetAllInstances(typeof(IEventHandler<>).MakeGenericType(x))));

        It should_have_all_events_mapped_to_the_appropriate_eventhandlers = () => _eventHandlerList.ForEach(x => { if(x.Value.Count == 0) throw new SpecificationException("There is no eventhandler for event '" + x.Key + "'"); });
    }
}